from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers

from main.system.models import Role
from main.utils.util_response import SuccessResponse
from main.utils.util_db import MySqlHandler
import main.migrates.sql as table_sql


class RoleSerializer(serializers.ModelSerializer):
    # 重写字段格式
    update_time=serializers.DateTimeField(format='%Y-%m-%d %H:%M:%S')
    class Meta:
        model=Role
        fields=['name','role_key','is_admin','description','update_time']


class RoleListView(APIView):
    def get(self, request):
        handler = MySqlHandler('default')
        roles = [item for item in handler.query( table_sql.SQL_ROLE)]
        # return SuccessResponse(data=get_json_from_file('mockdata/roles.json'))
        return SuccessResponse(data=roles)


class RoleDetailView(APIView):
    def get(self, request):
        roles = Role.objects.all()
        # 将对象序列化为python对象类型
        rs=RoleSerializer(instance=roles, many=True)
        # return Response({'code': 20000, 'msg': '获取成功', 'roles':json.loads(serializers.serialize('json',roles))})
        return Response({'code': 20000, 'msg': '获取成功', 'roles':rs.data})
    

    def post(self, request):
        name=request.data['name']
        role=Role.objects.create(name=name)
        role.save()
        return Response({'code': 20000, 'msg': '添加成功'})

    def put(self, request):
        return Response({'code': 20000, 'msg': '修改成功'})

    def delete(self, request):
        print(request.data)
        # Role.objects.filter(role_key=request.data.get('id'))
        return Response({'code': 20000, 'msg': '删除成功'})
